package com.baibei.product.trade;

import android.content.Context;
import android.os.CountDownTimer;
import android.text.TextUtils;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.quotation.AppQuotationFilter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.ITradeEvent;
import com.baibei.ebec.sdk.ApiErrorCode;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.Area;
import com.baibei.model.BalanceInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.TradeParams;
import com.baibei.model.TradeType;
import com.baibei.model.TradeWebSocketInfo;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.ApiException;
import com.baibei.sdk.Empty;
import com.blankj.utilcode.utils.LogUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import io.reactivex.Observable;

/**
 * 订购交易
 * Created by ChenRui on 2017/8/9 0009 10:24.
 */
public class TradePresenterImpl extends BasicPresenterImpl<TradeContract.View> implements TradeContract.Presenter, ITradeEvent {

    private ITradeApi mTradeApi;
    private IUserApi mUserApi;
    private CountDownTimer mCountDownTimer;
    private BalanceInfo mBalanceInfo;

    public TradePresenterImpl(Context context, TradeContract.View view) {
        super(context, view);
        mTradeApi = ApiFactory.getInstance().getTradeApi();
        mUserApi = ApiFactory.getInstance().getUserApi();
        QuotationFilter filter = new QuotationFilter(AppQuotationFilter.ACTION_TRADE_CLOSED);
        filter.addAction(AppQuotationFilter.ACTION_TRADE_CREATED);
        QuotationManager.getInstance().register(this, filter);

        // webSocket 超时
        mCountDownTimer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                if (mView != null) {
                    mView.onTradeTimeout();
                }
            }
        };
    }

    @Override
    public void destroy() {
        QuotationManager.getInstance().unregister(this);
        super.destroy();
    }

    @Override
    public void loadBalance() {
        createObservable(mUserApi.getBalanceInfo())
                .subscribe(new ApiDefaultObserver<BalanceInfo>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(BalanceInfo balanceInfo) {
                        mBalanceInfo = balanceInfo;
                    }
                });
    }

    @Override
    public void trade() {
        TradeParams params = mView.getTradeParams();
        ProductInfo productInfo = mView.getProductInfo();
        if (productInfo == null || TextUtils.isEmpty(productInfo.getProductId())) {
            mView.onTradeFailed("产品不存在");
            return;
        }
        if (TextUtils.isEmpty(productInfo.getArea())) {
            mView.onTradeFailed("区域不能为空");
            return;
        }
        if (params.quantity <= 0) {
            mView.onTradeFailed("请输入订货数量");
            return;
        }
        if (mBalanceInfo == null) {
            mView.onTradeFailed("余额加载失败");
            return;
        }

        double amount = params.amount + params.fee; // 总价格

        // 余额不足----当不使用
        if (params.couponInfo == null && (mBalanceInfo.getBalance() <= 0 || mBalanceInfo.getBalance() < amount)) {
            mView.onNotMoney();
            return;
        }

        Observable<Empty> observable;
        if (params.type == TradeType.BUY) {
            observable = performBuy(params, productInfo);
        } else {
            observable = performSell(params, productInfo);
        }
        observable.subscribe(new ApiDefaultObserver<Empty>() {

            @Override
            public void onError(ApiException e) {
                if (ApiErrorCode.ERROR_TRADE_EXIST.equalsIgnoreCase(e.getCode())) {
                    mView.onTradeExist();
                    return;
                }
                super.onError(e);
            }

            @Override
            protected void onError(String s) {
                mView.onTradeFailed(s);
            }

            @Override
            protected void accept(Empty empty) {
                mCountDownTimer.cancel();
                mCountDownTimer.start(); // 等待消息推送过来
            }
        });
    }

    @Override
    public void cancel() {
        cancelRequest();
    }

    @Override
    public void resume() {
        loadBalance();
    }

    @Override
    public void getClosePrice() {
        createObservable(mTradeApi.getRankingList(Area.ALL.name())).subscribe(new ApiDefaultObserver<List<RankingInfo>>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(List<RankingInfo> rankingInfos) {
                mView.onGetRankingInfoSuccess(rankingInfos);
            }
        });
    }

    /**
     * 现价订货
     */
    private Observable<Empty> performBuy(TradeParams params, ProductInfo productInfo) {
        int isJuan = params.couponInfo == null ? 0 : 1;
        String couponId = params.couponInfo == null ? null : params.couponInfo.getCouponId();
        int couponType = params.couponInfo == null ? 0 : params.couponInfo.getCouponType();
        return createObservable(mTradeApi.buy(productInfo.getProductId(), productInfo.getArea(), params.quantity,params.amount,params.fee, params.upPercent, params.downPercent, isJuan, couponId, couponType));
    }

    /**
     * 结算价订货
     */
    private Observable<Empty> performSell(TradeParams params, ProductInfo productInfo) {
        int isJuan = params.couponInfo == null ? 0 : 1;
        String couponId = params.couponInfo == null ? null : params.couponInfo.getCouponId();
        int couponType = params.couponInfo == null ? 0 : params.couponInfo.getCouponType();
        return createObservable(mTradeApi.sell(productInfo.getProductId(), productInfo.getArea(), params.quantity, params.amount,params.fee,params.upPercent, params.downPercent, isJuan, couponId, couponType));
    }

    @Override
    @Subscribe
    public void onEvent(TradeWebSocketInfo tradeInfo) {
        LogUtils.e("订购websocket推送：" + tradeInfo);
        mCountDownTimer.cancel();
        if ("CODE_CREATE_SUCCESS".equalsIgnoreCase(tradeInfo.getCode())) {
            mView.onTradeSuccess(tradeInfo.getMsg());
        }
        if ("CODE_CREATE_FAIL".equalsIgnoreCase(tradeInfo.getCode())) {
            mView.onTradeFailed(tradeInfo.getMsg());
        }
    }

}
